<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';

import VehicleMileageRank from './VehicleMileageRank.vue';
import VehicleUsageTrend from './VehicleUsageTrend.vue';

// 筛选表单数据
const searchForm = ref({
  dateRange: [] as string[],
  department: '',
  licensePlate: '',
});

// 用车部门选项（模拟数据）
const departmentOptions = [
  { label: '技术部', value: 'technology' },
  { label: '销售部', value: 'sales' },
  { label: '市场部', value: 'marketing' },
  { label: '人事部', value: 'hr' },
  { label: '财务部', value: 'finance' },
];

// 日期快捷选项
const shortcuts = [
  {
    text: '本月',
    value: () => {
      const start = new Date();
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setHours(23, 59, 59, 999);
      return [start, end];
    },
  },
  {
    text: '本季度',
    value: () => {
      const start = new Date();
      const quarter = Math.floor(start.getMonth() / 3);
      start.setMonth(quarter * 3, 1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setMonth((quarter + 1) * 3, 0);
      end.setHours(23, 59, 59, 999);
      return [start, end];
    },
  },
  {
    text: '本年',
    value: () => {
      const start = new Date();
      start.setMonth(0, 1);
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setMonth(11, 31);
      end.setHours(23, 59, 59, 999);
      return [start, end];
    },
  },
];

// Mock统计数据
const statisticsData = ref({
  totalMileage: 125_600, // 总行驶里程（公里）
  totalTrips: 892, // 总出车次数
  averageMileage: 140.8, // 平均行驶里程（公里）
  mostUsedVehicle: '京A12345', // 出车频率最高的车辆
});

// Mock车辆里程排名数据
const mileageRankData = ref([
  { licensePlate: '京A12345', mileage: 15_600 },
  { licensePlate: '京B67890', mileage: 14_200 },
  { licensePlate: '京C11111', mileage: 13_800 },
  { licensePlate: '京D22222', mileage: 12_500 },
  { licensePlate: '京E33333', mileage: 11_900 },
  { licensePlate: '京F44444', mileage: 10_800 },
  { licensePlate: '京G55555', mileage: 9600 },
  { licensePlate: '京H66666', mileage: 8900 },
  { licensePlate: '京I77777', mileage: 8200 },
  { licensePlate: '京J88888', mileage: 7500 },
]);

// Mock用车趋势数据
const usageTrendData = ref({
  dates: ['1月', '2月', '3月', '4月', '5月', '6月'],
  mileage: [18_000, 19_500, 17_200, 21_000, 22_500, 20_800],
  timeUnit: 'month',
});

// 生成Mock数据的函数
const generateMockData = () => {
  const vehicles = [
    '京A12345',
    '京B67890',
    '京C11111',
    '京D22222',
    '京E33333',
    '京F44444',
    '京G55555',
    '京H66666',
    '京I77777',
    '京J88888',
  ];

  const drivers = [
    '张三',
    '李四',
    '王五',
    '赵六',
    '钱七',
    '孙八',
    '周九',
    '吴十',
  ];
  const users = [
    '用户A',
    '用户B',
    '用户C',
    '用户D',
    '用户E',
    '用户F',
    '用户G',
    '用户H',
  ];
  const departments = ['技术部', '销售部', '市场部', '人事部', '财务部'];

  const records = [];
  const totalRecords = 150; // 生成150条记录用于测试分页

  for (let i = 1; i <= totalRecords; i++) {
    const vehicle = vehicles[Math.floor(Math.random() * vehicles.length)];
    const driver = drivers[Math.floor(Math.random() * drivers.length)];
    const user = users[Math.floor(Math.random() * users.length)];
    const department =
      departments[Math.floor(Math.random() * departments.length)];

    // 生成随机时间
    const startDate = new Date(
      2024,
      0,
      Math.floor(Math.random() * 31) + 1,
      Math.floor(Math.random() * 12) + 8,
      0,
    );
    const endDate = new Date(
      startDate.getTime() + Math.floor(Math.random() * 8) * 60 * 60 * 1000,
    );

    records.push({
      id: i,
      licensePlate: vehicle,
      driver,
      user,
      department,
      startTime: startDate.toISOString().slice(0, 16).replace('T', ' '),
      endTime: endDate.toISOString().slice(0, 16).replace('T', ' '),
      mileage: Math.floor(Math.random() * 300) + 50, // 50-350公里
    });
  }

  return records;
};

// Mock数据明细
const tableData = ref(generateMockData());

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
  total: tableData.value.length,
});

// 每页条数选项
const pageSizeOptions = [10, 15, 20, 25, 30, 50];

// 筛选后的数据（未分页）
const filteredTableData = computed(() => {
  let data = tableData.value;

  // 按日期范围筛选
  if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
    const [start, end] = searchForm.value.dateRange;
    data = data.filter((record) => {
      const recordDate = new Date(record.startTime);
      const startDate = new Date(start);
      const endDate = new Date(end);
      return recordDate >= startDate && recordDate <= endDate;
    });
  }

  // 按用车部门筛选
  if (searchForm.value.department) {
    data = data.filter(
      (record) => record.department === searchForm.value.department,
    );
  }

  // 按车牌号模糊搜索
  if (searchForm.value.licensePlate) {
    const keyword = searchForm.value.licensePlate.toLowerCase();
    data = data.filter((record) =>
      record.licensePlate.toLowerCase().includes(keyword),
    );
  }

  return data;
});

// 分页后的数据
const paginatedTableData = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize;
  const end = start + pagination.value.pageSize;
  return filteredTableData.value.slice(start, end);
});

// 更新分页总数
const updatePagination = () => {
  pagination.value.total = filteredTableData.value.length;
  pagination.value.currentPage = 1; // 重置到第一页
};

// 计算属性 - 数据概览卡片
const overviewCards = computed(() => [
  {
    title: '总行驶里程',
    value: statisticsData.value.totalMileage.toLocaleString(),
    unit: '公里',
    icon: '🚗',
    color: 'bg-blue-500',
  },
  {
    title: '总出车次数',
    value: statisticsData.value.totalTrips.toLocaleString(),
    unit: '次',
    icon: '📊',
    color: 'bg-green-500',
  },
  {
    title: '平均行驶里程',
    value: statisticsData.value.averageMileage.toFixed(1),
    unit: '公里',
    icon: '📈',
    color: 'bg-purple-500',
  },
  {
    title: '最活跃车辆',
    value: statisticsData.value.mostUsedVehicle,
    unit: '',
    icon: '🏆',
    color: 'bg-yellow-500',
  },
]);

// 监听筛选条件变化，更新数据
watch(
  () => searchForm.value,
  () => {
    updatePagination();
    // 这里可以添加更新图表数据的逻辑
  },
  { deep: true },
);

// 处理查询
const handleSearch = () => {
  console.log('查询条件:', searchForm.value);
  // 筛选逻辑已经在computed中处理
};

// 处理重置
const handleReset = () => {
  searchForm.value = {
    dateRange: [],
    department: '',
    licensePlate: '',
  };
  handleSearch();
};

// 处理导出
const handleExport = () => {
  // 获取当前日期用于文件名
  const today = new Date();
  const dateStr = today.toISOString().slice(0, 10).replaceAll('-', '');

  // 准备导出数据
  const exportData = filteredTableData.value.map((record) => ({
    车牌号: record.licensePlate,
    司机: record.driver,
    用车人: record.user,
    用车部门: record.department,
    开始时间: record.startTime,
    结束时间: record.endTime,
    行驶里程: `${record.mileage} 公里`,
  }));

  // 创建CSV内容
  const headers = [
    '车牌号',
    '司机',
    '用车人',
    '用车部门',
    '开始时间',
    '结束时间',
    '行驶里程',
  ];
  const csvContent = [
    headers.join(','),
    ...exportData.map((row) =>
      headers
        .map((header) => {
          const value = row[header];
          // 如果值包含逗号，用双引号包围
          return value && value.toString().includes(',')
            ? `"${value}"`
            : value || '';
        })
        .join(','),
    ),
  ].join('\n');

  // 创建下载链接
  const blob = new Blob([`\uFEFF${csvContent}`], {
    type: 'text/csv;charset=utf-8;',
  });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', `车辆使用统计报表_${dateStr}.csv`);
  link.style.visibility = 'hidden';
  document.body.append(link);
  link.click();
  link.remove();

  console.log('数据导出成功');
};

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.value.currentPage = page;
  // 这里应该调用API获取新页面数据
};

// 处理每页条数变化
const handlePageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.currentPage = 1; // 切换条数时重置到第一页
  // 这里应该调用API获取新条数的数据
};

// 车辆详情模态框相关
const dialogVisible = ref(false);
const currentVehicleDetail = ref(null);

// 处理查看车辆详情
const handleViewDetail = (row: any) => {
  currentVehicleDetail.value = row;
  dialogVisible.value = true;
};

// 计算用车时长
const calculateDuration = (startTime: string, endTime: string): string => {
  const start = new Date(startTime);
  const end = new Date(endTime);
  const diffMs = end.getTime() - start.getTime();
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));

  return diffHours > 0
    ? `${diffHours}小时${diffMinutes}分钟`
    : `${diffMinutes}分钟`;
};

// 处理排序
const handleSort = (column: any) => {
  console.log('排序:', column.prop, column.order);
  // 这里应该调用API获取排序后的数据
};
</script>

<template>
  <div class="min-h-screen bg-gray-50 p-5">
    <!-- 筛选区域 -->
    <ElCard class="mb-5 rounded-xl border-0 shadow-lg">
      <ElForm
        ref="searchFormRef"
        :model="searchForm"
        :inline="true"
        class="search-form"
      >
        <div class="flex flex-wrap items-center gap-4">
          <ElFormItem
            label="日期范围"
            prop="dateRange"
            class="min-w-[200px] flex-1"
          >
            <ElDatePicker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :shortcuts="shortcuts"
              class="w-full"
            />
          </ElFormItem>

          <ElFormItem
            label="用车部门"
            prop="department"
            class="min-w-[150px] flex-1"
          >
            <ElSelect
              v-model="searchForm.department"
              placeholder="请选择用车部门"
              clearable
              class="w-full"
            >
              <ElOption
                v-for="item in departmentOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </ElFormItem>

          <ElFormItem
            label="车牌号"
            prop="licensePlate"
            class="min-w-[150px] flex-1"
          >
            <ElInput
              v-model="searchForm.licensePlate"
              placeholder="请输入车牌号"
              clearable
              @keyup.enter="handleSearch"
              class="w-full"
            />
          </ElFormItem>

          <div class="flex gap-2">
            <ElButton type="primary" @click="handleSearch" class="px-4">
              查询
            </ElButton>
            <ElButton @click="handleReset" class="px-4"> 重置 </ElButton>
            <ElButton type="success" @click="handleExport" class="px-4">
              导出
            </ElButton>
          </div>
        </div>
      </ElForm>
    </ElCard>

    <!-- 数据概览区 -->
    <div class="mb-5 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
      <ElCard
        v-for="card in overviewCards"
        :key="card.title"
        class="rounded-xl border-0 shadow-lg transition-shadow duration-300 hover:shadow-xl"
      >
        <div class="flex items-center justify-between">
          <div>
            <p class="mb-1 text-sm text-gray-600">{{ card.title }}</p>
            <p class="text-2xl font-bold text-gray-800">
              {{ card.value }}
              <span v-if="card.unit" class="ml-1 text-sm text-gray-500">{{
                card.unit
              }}</span>
            </p>
          </div>
          <div :class="`rounded-lg p-3 text-3xl ${card.color} text-white`">
            {{ card.icon }}
          </div>
        </div>
      </ElCard>
    </div>

    <!-- 图表展示区 -->
    <div class="mb-5 grid grid-cols-1 gap-5 lg:grid-cols-2">
      <!-- 车辆里程排名 -->
      <ElCard class="rounded-xl border-0 shadow-lg">
        <div class="p-4">
          <h3 class="mb-4 text-lg font-semibold text-gray-800">
            车辆里程排名（前10）
          </h3>
          <VehicleMileageRank :data="mileageRankData" />
        </div>
      </ElCard>

      <!-- 用车趋势 -->
      <ElCard class="rounded-xl border-0 shadow-lg">
        <div class="p-4">
          <div class="mb-4 flex items-center justify-between">
            <h3 class="text-lg font-semibold text-gray-800">用车趋势</h3>
            <ElSelect
              v-model="usageTrendData.timeUnit"
              placeholder="时间粒度"
              class="w-24"
            >
              <ElOption label="按天" value="day" />
              <ElOption label="按月" value="month" />
            </ElSelect>
          </div>
          <VehicleUsageTrend :data="usageTrendData" />
        </div>
      </ElCard>
    </div>

    <!-- 数据明细区 -->
    <ElCard class="rounded-xl border-0 shadow-lg">
      <div class="p-4">
        <h3 class="mb-4 text-lg font-semibold text-gray-800">用车明细</h3>
        <ElTable
          :data="paginatedTableData"
          class="vehicle-table overflow-hidden rounded-lg"
          :header-cell-style="{
            background: '#f8fafc',
            color: '#374151',
            fontWeight: '600',
            borderBottom: '2px solid #e5e7eb',
          }"
          :cell-style="{ borderBottom: '1px solid #f1f5f9' }"
          @sort-change="handleSort"
        >
          <ElTableColumn type="index" label="序号" width="60" align="center">
            <template #default="{ $index }">
              <span class="font-medium text-gray-500">{{ $index + 1 }}</span>
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="licensePlate"
            label="车牌号"
            sortable
            width="120"
            align="center"
          />
          <ElTableColumn
            prop="driver"
            label="司机"
            sortable
            width="100"
            align="center"
          />
          <ElTableColumn
            prop="user"
            label="用车人"
            sortable
            width="100"
            align="center"
          />
          <ElTableColumn
            prop="department"
            label="用车部门"
            sortable
            width="120"
            align="center"
          >
            <template #default="{ row }">
              <ElTag>{{ row.department }}</ElTag>
            </template>
          </ElTableColumn>
          <ElTableColumn
            prop="startTime"
            label="开始时间"
            sortable
            width="150"
            align="center"
          />
          <ElTableColumn
            prop="endTime"
            label="结束时间"
            sortable
            width="150"
            align="center"
          />
          <ElTableColumn
            prop="mileage"
            label="行驶里程"
            sortable
            width="120"
            align="center"
          >
            <template #default="{ row }"> {{ row.mileage }} 公里 </template>
          </ElTableColumn>
          <ElTableColumn label="操作" width="100" align="center" fixed="right">
            <template #default="{ row }">
              <ElButton
                type="primary"
                size="small"
                @click="handleViewDetail(row)"
                class="font-medium text-blue-600 hover:text-blue-800"
              >
                查看
              </ElButton>
            </template>
          </ElTableColumn>
        </ElTable>

        <!-- 分页 -->
        <div class="mt-4 flex items-center justify-between">
          <div class="flex items-center gap-4">
            <span class="text-sm text-gray-600">
              显示
              {{ (pagination.currentPage - 1) * pagination.pageSize + 1 }} 到
              {{
                Math.min(
                  pagination.currentPage * pagination.pageSize,
                  pagination.total,
                )
              }}
              条，共 {{ pagination.total }} 条
            </span>
            <ElSelect
              v-model="pagination.pageSize"
              @change="handlePageSizeChange"
              class="w-20"
              size="small"
            >
              <ElOption
                v-for="size in pageSizeOptions"
                :key="size"
                :label="`${size} 条/页`"
                :value="size"
              />
            </ElSelect>
          </div>
          <ElPagination
            v-model:current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            @current-change="handlePageChange"
            layout="prev, pager, next, jumper"
            background
          />
        </div>
      </div>
    </ElCard>

    <!-- 车辆详情模态框 -->
    <ElDialog
      v-model="dialogVisible"
      :title="`${currentVehicleDetail?.licensePlate} 用车明细`"
      width="600px"
      :before-close="
        () => {
          dialogVisible = false;
        }
      "
      class="vehicle-detail-dialog"
    >
      <div v-if="currentVehicleDetail" class="p-4">
        <ElForm
          :model="currentVehicleDetail"
          label-width="120px"
          label-position="left"
          class="vehicle-detail-form"
        >
          <ElFormItem label="车牌号：">
            <span class="font-mono font-semibold text-gray-800">{{
              currentVehicleDetail.licensePlate
            }}</span>
          </ElFormItem>
          <ElFormItem label="司机：">
            <span class="text-gray-700">{{ currentVehicleDetail.driver }}</span>
          </ElFormItem>
          <ElFormItem label="用车人：">
            <span class="text-gray-700">{{ currentVehicleDetail.user }}</span>
          </ElFormItem>
          <ElFormItem label="用车部门：">
            <ElTag>{{ currentVehicleDetail.department }}</ElTag>
          </ElFormItem>
          <ElFormItem label="开始时间：">
            <span class="text-gray-600">{{
              currentVehicleDetail.startTime
            }}</span>
          </ElFormItem>
          <ElFormItem label="结束时间：">
            <span class="text-gray-600">{{
              currentVehicleDetail.endTime
            }}</span>
          </ElFormItem>
          <ElFormItem label="行驶里程：">
            <span class="font-medium text-gray-700">{{ currentVehicleDetail.mileage }} 公里</span>
          </ElFormItem>
          <ElFormItem label="用车时长：">
            <span class="text-gray-600">
              {{
                calculateDuration(
                  currentVehicleDetail.startTime,
                  currentVehicleDetail.endTime,
                )
              }}
            </span>
          </ElFormItem>
        </ElForm>
      </div>
    </ElDialog>
  </div>
</template>

<style scoped>


/* 响应式优化 */
@media (max-width: 768px) {
  .flex-wrap {
    flex-direction: column;
    align-items: stretch;
  }

  .grid-cols-4 {
    grid-template-columns: repeat(2, 1fr);
  }

  .grid-cols-2 {
    grid-template-columns: 1fr;
  }
}

:deep(.vehicle-table) {
  overflow: hidden;
  background: #fff;
  border-radius: 12px;
  box-shadow:
    0 4px 6px -1px rgb(0 0 0 / 10%),
    0 2px 4px -1px rgb(0 0 0 / 6%);
}

:deep(.vehicle-table .el-table__header-wrapper) {
  border-radius: 12px 12px 0 0;
}

:deep(.vehicle-table .el-table__body-wrapper) {
  border-radius: 0 0 12px 12px;
}

:deep(.vehicle-table .el-table__row:nth-child(even)) {
  background-color: #f9fafb;
}

/* 自定义样式 */
:deep(.search-form .el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-select__wrapper) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
  transition: all 0.2s ease;
}

:deep(.el-button) {
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.2s ease;
}

:deep(.el-card) {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
}

:deep(.el-table) {
  overflow: hidden;
  border-radius: 8px;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}

/* 自定义表格样式 */
</style>
